const { TenantContext } = require('@/core/tenant-context');

/**
 * 操作日志
 */
class OperationLogger {
    constructor(db) {
        this.db = db;
    }

    // 日志表名
    static table_name = 'system_user_operation_logs';

    /**
     * 创建日志
     * @param {*} logData 
     * @returns 
     */
    async create(logData = {}) {
        const sql = `
            INSERT INTO ${OperationLogger.table_name} (
                trace_id, user_id, username, user_type, tenant_id, shop_id, description, 
                ip_address, user_agent, device_id, module, operation, 
                request_uri, request_method, request_params, request_query, request_body, 
                response_data, state_before, state_after, status, error_code, 
                error_msg, execution_time, created_by 
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `;
        const values = [
            logData.traceId,
            logData.userId,
            logData.username,
            logData.userType,
            logData.tenantId,
            logData.shopId,
            logData.description,
            logData.ip,
            logData.userAgent,
            logData.deviceId,
            logData.module,
            logData.operation,
            logData.requestUri,
            logData.requestMethod,
            JSON.stringify(logData.requestParams || {}),
            JSON.stringify(logData.requestQuery || {}),
            JSON.stringify(logData.requestBody || {}),
            JSON.stringify(logData.responseData || {}),
            JSON.stringify(logData.stateBefore || {}),
            JSON.stringify(logData.stateAfter || {}),
            logData.status,
            logData.errorCode,
            logData.errorMsg,
            logData.executionTime,
            TenantContext.getCurrentUser() || ''
        ];
        const result = await this.db.query(sql, values);
        if (result.code === 200) {
            return true;
        }
        return false;
    }
}

module.exports = OperationLogger;